<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- <template slot="before"> -->
        <!-- <template v-slot:before> -->
        <template #before>
          共{{ total }}条记录
        </template>
        <template #after>
          <el-button size="small" type="warning" @click=" $router.push('/employees/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column prop="index" type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="scope">
              <!-- active-value	switch 打开时的值 -->
              <!-- inactive-value	switch 关闭时的值 -->
              <el-switch
                :value="scope.row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageConfig.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <add-employess
        :is-show-dialog="isShowDialog"
        @load="loadPage"
        @isShowDialog="isShowDialog=false"
      />
      <!-- 角色 -->
      <assign-role ref="assignRole" :is-show-role-dialog="isShowRoleDialog" @closeDialog="isShowRoleDialog=false" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
// 引入 导出excel函数
import { export_json_to_excel } from '@/vendor/Export2Excel'
// 引入过滤器函数
import { formatDate } from '@/filters/index'
// 引入添加员工弹框
import AddEmployess from './components/AddEmployess.vue'
// 角色详情弹窗
import AssignRole from './components/AssignRole.vue'
export default {
  components: { AddEmployess, AssignRole },
  data() {
    return {
      // 分页配置
      pageConfig: {
        page: 1,
        size: 5
      },
      total: 0,
      list: [],
      isShowDialog: false,
      isShowRoleDialog: false// 角色
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    async loadPage() {
      const { rows, total } = await getEmployeeList(this.pageConfig)
      // this.list = rows
      // 这里是获取员工的地方
      // 如果后端给出的数据跟我们预期有出入, 可以再这里进行修改
      // 这里咱们处理一下序号, 希望每个员工都自带序号
      this.list = rows.map((item, index) => {
        return {
          ...item,
          index: (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
        }
      })
      this.total = total
    },
    // 分页
    currentChange(newPage) {
      this.pageConfig.page = newPage// 把点击最新页放入分页配置
      this.loadPage()// 重新渲染页面
    },
    // 聘用形势数据转换
    formatEmployment(row, col, val, index) {
      const result = EmployeeEnum.hireType.find(item => item.id === val)
      return result ? result.value : '未知'
    },
    // 导出excel文件
    async  exportExcel() {
      // 1.获取所有员工数据
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.total
      })
      console.log(rows)
      // 定义字典  以键值对的方式 表头和对应要拿的数据字段名
      const dict = {
        '用户名': 'username',
        '手机号': 'moblie',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      // 获取表头
      const header = Object.keys(dict)// // 返回以数组的形式存入
      const data = rows.map(item => {
        // 映射后端拿到的员工数据, 每个员工数据现在都叫 item
        const user = []
        for (const zhKey in dict) {
          const enKey = dict[zhKey]// dict对象中zhKey键的值 如username
          const value = item[enKey]
          // 两处需要特殊处理
          if (enKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(el => el.id === value)
            user.push(obj ? obj.value : '未知')
          } else if (enKey === 'timeOfEntry') {
            user.push(formatDate(value))
          } else {
            user.push(value)
          }
        }
        return user
      })

      // 2. 转成 excel 文件供用户下载
      export_json_to_excel({
        header,
        data
      })
    },
    // 删除员工
    async delEmployee(id) {
      // 二次询问
      await this.$confirm('是否要删除此员工')
      // 发送请求
      await delEmployee(id)
      // 弹框提示
      this.$message.success('删除成功')
      // 重新渲染页面
      this.loadPage()
    },
    // 角色
    async showRoleDialog(id) {
      // 显示角色弹窗的时候，自动回显选中原来的角色
      await this.$refs.assignRole.getUSerDetail(id)
      this.isShowRoleDialog = true
    }
  }
}
</script>

  <style>

  </style>
